/**
 * @description 首页表格
 * @author chengpeng
 */
import React, { Component } from 'react';
import Record from './Record'
import RecordFrom from './RecordFrom'
import AmountBox from './AmountBox'
import axios from 'axios'
import * as RecordsApi from '../utils/RecordsApi'

class Records extends Component {
  constructor() {
    super()
    this.state = {
      records: [], // http://localhost:3000/api/recordList.json
      loading: true,
      err: null
    }
  }

  componentDidMount() {
    // RecordsApi.getAll().then(res => console.log(res))
    axios.get(`${RecordsApi.api}/api/recordList.json`).then(res => {
      if(res.status === 200 && res.data.errCode === 0) {
        this.setState({
          records: res.data.recordsList,
          loading: false
        })
      }
    }).catch(err => {
      this.setState({
        loading: false,
        err
      })
    })
  }

  // 子组件数据接收
  addRecord(result) {
    this.setState({
      records: [
        ...this.state.records,
        result
      ],
      loading: true,
      err: null
    })
  }

  updateRecord(result, data) {
    const recordIndex = this.state.records.indexOf(result);
    const newRecords = this.state.records.map((item, index) => {
      if(index !== recordIndex) {
        return item;
      }
      return {
        ...item,
        ...data
      }
    })
    this.setState({
      records: newRecords
    })
  }

  deleteRecord(result) {
    const recordIndex = this.state.records.indexOf(result)
    const newRecords = this.state.records.filter((item, index) => index !== recordIndex)
    this.setState({
      records: newRecords
    })
  }

  credits() {
    let credits = this.state.records.filter(item => {
      return item.amount >= 0
    })
    return credits.reduce((prev, curr) => {
      return prev + Number.parseInt(curr.amount)
    }, 0)
  }

  debits() {
    let debits = this.state.records.filter(item => {
      return item.amount < 0
    })
    return debits.reduce((prev, curr) => {
      return prev + Number.parseInt(curr.amount)
    }, 0)
  }

  balance() {
    return this.credits() + this.debits()
  }

  render() {
    const {loading, err, records} = this.state
    let recordsComponent

    if(err) {
      recordsComponent = <div>Error: {err.message}</div>
    } else if(loading) {
      recordsComponent = <div>Loading...</div>
    } else {
      recordsComponent = <table className="table table-bordered">
            <thead>
              <tr>
                <th>Date</th>
                <th>Title</th>
                <th>Amount</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {records.map((item, index) => (
                  <Record key={item.id} record={item} handleEditRecord={this.updateRecord.bind(this)} handleDeleteRecord={this.deleteRecord.bind(this)} /> 
                )
              )}
            </tbody>
          </table>
    }
    return (
      <div>
        <h2>Records</h2>
        <div className="row mb-3">
          <AmountBox text="Credits" amount={this.credits()} type="success" />
          <AmountBox text="Debits" amount={this.debits()} type="danger" />
          <AmountBox text="Balance" amount={this.balance()} type="info" />
        </div>
        <RecordFrom handleNewRecord={this.addRecord.bind(this)} />
        {recordsComponent}
        </div>
      );
  }
}

export default Records;
